from sqlalchemy import Column, Integer, String, Float, Text, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import datetime
import json

Base = declarative_base()

class FileIndex(Base):
    """文件索引模型"""
    __tablename__ = 'file_index'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    path = Column(String(500), unique=True, nullable=False)
    file_hash = Column(String(64), nullable=False)
    size = Column(Integer, nullable=False)
    created_time = Column(Float, nullable=False)
    modified_time = Column(Float, nullable=False)
    project = Column(String(100), default='')
    extra = Column(Text, default='{}')  # JSON格式的扩展字段
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            "id": self.id,
            "path": self.path,
            "file_hash": self.file_hash,
            "size": self.size,
            "created_time": datetime.datetime.fromtimestamp(self.created_time),
            "modified_time": datetime.datetime.fromtimestamp(self.modified_time),
            "project": self.project,
            "extra": self.extra
        }

class SyncMeta(Base):
    """同步元数据模型"""
    __tablename__ = 'sync_meta'
    
    key = Column(String(50), primary_key=True)
    value = Column(String(200), nullable=False)
    context = Column(Text, default='{}')  # JSON格式的上下文
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            "key": self.key,
            "value": self.value,
            "context": self.context
        }

class DatabaseManager:
    """数据库管理器（无SQL版本）"""
    
    def __init__(self, db_url="sqlite:///file_index.db"):
        self.engine = create_engine(db_url)
        self.Session = sessionmaker(bind=self.engine)
        
        # 自动创建表（仅用于开发环境）
        Base.metadata.create_all(self.engine)
    
    def add_file(self, path, file_hash, size, created, modified, project=None, extra=None):
        """添加文件记录"""
        session = self.Session()
        try:
            file = FileIndex(
                path=path,
                file_hash=file_hash,
                size=size,
                created_time=created,
                modified_time=modified,
                project=project or "",
                extra=json.dumps(extra or {})
            )
            session.add(file)
            session.commit()
            return file.id
        except Exception as e:
            session.rollback()
            raise e
        finally:
            session.close()
    
    def delete_file(self, path):
        """删除文件记录"""
        session = self.Session()
        try:
            file = session.query(FileIndex).filter_by(path=path).first()
            if file:
                session.delete(file)
                session.commit()
                return True
            return False
        except Exception as e:
            session.rollback()
            raise e
        finally:
            session.close()
    
    def get_last_event_id(self):
        """获取最后事件ID"""
        session = self.Session()
        try:
            meta = session.query(SyncMeta).filter_by(key='last_event_id').first()
            return int(meta.value) if meta else 0
        finally:
            session.close()
    
    def set_last_event_id(self, event_id, context=None):
        """设置最后事件ID"""
        session = self.Session()
        try:
            meta = session.query(SyncMeta).filter_by(key='last_event_id').first()
            if meta:
                meta.value = str(event_id)
                meta.context = json.dumps(context or {})
            else:
                meta = SyncMeta(
                    key='last_event_id',
                    value=str(event_id),
                    context=json.dumps(context or {})
                )
                session.add(meta)
            session.commit()
        except Exception as e:
            session.rollback()
            raise e
        finally:
            session.close()
    
    def search_files(self, keyword, project=None):
        """搜索文件"""
        session = self.Session()
        try:
            query = session.query(FileIndex)
            
            if keyword:
                query = query.filter(FileIndex.path.like(f"%{keyword}%"))
            
            if project:
                query = query.filter_by(project=project)
            
            return [file.to_dict() for file in query.limit(200).all()]
        finally:
            session.close()
    
    # MCP预留接口
    def get_project_files(self, project):
        """按项目获取文件"""
        session = self.Session()
        try:
            files = session.query(FileIndex).filter_by(project=project).all()
            return [file.to_dict() for file in files]
        finally:
            session.close()
    
    def add_context_info(self, path, context):
        """添加上下文信息"""
        session = self.Session()
        try:
            file = session.query(FileIndex).filter_by(path=path).first()
            if file:
                extra = json.loads(file.extra or "{}")
                extra.update(context)
                file.extra = json.dumps(extra)
                session.commit()
                return True
            return False
        except Exception as e:
            session.rollback()
            raise e
        finally:
            session.close()